package com.yindian.cos.logging.elastic;

import org.apache.logging.log4j.Level;
import org.elasticsearch.action.bulk.BulkProcessor;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RestHighLevelClient;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 向elasticsearch输出日志逻辑
 *
 * @author zhangchuanhao
 * @create 2018/11/1
 */
public class ElasticsearchUtil {

    /**
     * 向elasticsearch写入日志数据
     *
     * @param source
     * @return
     */
    public static void index(BulkProcessor bulkProcessor, Map<String, Object> source, String index, String type) {
        String indexFormat = index.indexOf('\'') < 0 ? index : getIndexNameDateFormat(index).format(new Date());
        if (source.containsKey("level")) {
            Level level = (Level) source.get("level");
            source.put("level", level.name());
        }
        IndexRequest indexRequest = new IndexRequest(indexFormat).type(type).source(source);
        bulkProcessor.add(indexRequest);
    }

    /**
     * 关闭连接
     */
    public static void close(RestHighLevelClient client, BulkProcessor bulkProcessor) {
        bulkProcessor.close();
        try {
            client.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 保证线程安全
     */
    private static final ThreadLocal<Map<String, SimpleDateFormat>> df = ThreadLocal.withInitial(HashMap::new);

    private static SimpleDateFormat getIndexNameDateFormat(String index) {
        Map<String, SimpleDateFormat> formatters = df.get();
        SimpleDateFormat formatter = formatters.get(index);
        if (formatter == null) {
            formatter = new SimpleDateFormat();
            formatter.applyPattern(index);
            formatters.put(index, formatter);
        }
        return formatter;
    }
}
